// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// G [author] rhyme_lph
// s [email]  rhymelph@gmail.com
// U [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/purchase_order_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/purchase_order_number_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/purchase/purchase_order_number_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

export 'package:finance_app/src/entities/purchase_order_entity.dart';

@RouterMeta(paramName: "purchaseOrderNumberPage")
class PurchaseOrderNumberPage extends StatefulWidget {
  final int contactId;
  final PurchaseOrderEntity select;

  const PurchaseOrderNumberPage({Key key, this.contactId, this.select})
      : super(key: key);

  @override
  _PurchaseOrderNumberPageState createState() =>
      _PurchaseOrderNumberPageState();
}

class _PurchaseOrderNumberPageState extends State<PurchaseOrderNumberPage>
    with PagePresenter<PurchaseOrderNumberPage, PurchaseOrderNumberProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.purchase_order_number,
      );

  @override
  void initState() {
    provider.currentSelect = widget.select;
    provider.contactId = widget.contactId;
    super.initState();
  }

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            _buildTopWidget(),
            Expanded(child: super.buildEmptyWidget),
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTopWidget(),
            Expanded(
              child: listBuilder<List<PurchaseOrderEntity>>(
                selector: (_, __) => __.data,
                builder: (BuildContext context, List<PurchaseOrderEntity> value,
                        Widget child) =>
                    value.isEmpty
                        ? super.buildEmptyWidget
                        : SmartRefresher(
                            controller: provider.refreshController,
                            onRefresh: provider.onRefresh,
                            onLoading: provider.onLoadMore,
                            enablePullUp: provider.hasUp,
                            child: ListView(
                              children: buildChildList(),
                            ),
                          ),
              ),
            ),
          ],
        ),
      );

  List<Widget> buildChildList() {
    return provider.data.toList().map((e) => buildSliverItem(e)).toList();
  }

  Widget buildSliverItem(PurchaseOrderEntity data) {
    return listBuilder<Tuple2<PurchaseOrderEntity, bool>>(
      selector: (_, __) => Tuple2(data, data.id == __.currentSelect?.id),
      builder: (BuildContext context, Tuple2<PurchaseOrderEntity, bool> value,
              Widget child) =>
          PressedOpacityButton(
        onPressed: () => provider.onSelect(value.item1),
        child: PurchaseOrderNumberRadio(
          title: value.item1?.contact?.name ?? '',
          poNumber: value.item1.number,
          delivery: DateTimeUtils.formatDateTimeString(value.item1.deliveryAt),
          amount: value.item1.total.toDouble(),
          status: FormUtils.getStatus(
              TransactionTypeUtils.getTransactionTypeStatus(
                  value.item1.dataType),
              value.item1.status,
              0),
          unit: value.item1.currencyCode,
          isSelect: value.item2,
        ),
      ),
    );
  }

  Widget _buildTopWidget() {
    return Column(
      children: [
        AppSpaces.h20,
        SearchInputField(
          controller: provider.searchController,
          focusNode: provider.searchFocusNode,
        ),
        Config.hasPermission(PermissionUtils.purchaseOrder)
            ? Column(
                children: [
                  NormalFormWrapper(
                    child: AddButton(
                      title: S.current.add_purchase_order,
                      onTap: provider.onNavAddPurchaseOrder,
                    ),
                  ),
                  AppSpaces.grayH05,
                ],
              )
            : AppSpaces.h20,
      ],
    );
  }
}
